import logging

from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *

logger = logging.getLogger(__name__)

#  https://www.pythonguis.com/tutorials/creating-multiple-windows/
class ConsoleWindow(QWidget):
    """
    This "window" is a QWidget. If it has no parent, it
    will appear as a free-floating window as we want.
    """

    widgetHidden = pyqtSignal()
    widgetShown = pyqtSignal()

    def __init__(self, title='Console'):
        super().__init__()
        layout = QVBoxLayout()
        self.setWindowTitle(title)
        self.log_display = QTextEdit()
        self.log_display.setReadOnly(True)
        layout.addWidget(self.log_display)
        self.log_handler = ConsoleLogHandler(self.log_display)
        logging.getLogger().addHandler(self.log_handler)
        self.formatter = logging.Formatter('[%(asctime)s] %(name)s - %(levelname)s: %(message)s')
        self.formatter.datefmt = '%m/%d/%Y %I:%M:%S'
        self.log_handler.setFormatter(self.formatter)
        self.setLayout(layout)

        logger.info('Console initialized')

    def closeEvent(self, event):
        event.ignore()
        self.hide()
        logger.info('Console hidden')

    def close(self):
        self.log_handler.close()
        returnVal = QWidget.close(self)
        logger.info('Console closed')
        return returnVal

    def hide(self):
        self.widgetHidden.emit()
        QWidget.hide(self)

    def show(self):
        self.widgetShown.emit()
        QWidget.show(self)

    @staticmethod
    def new_window(title='Console'):
        window = ConsoleWindow(title)
        window.showMaximized()
        return window

class ConsoleLogHandler(logging.Handler):
    def __init__(self, widget: QTextEdit):
        super().__init__()
        self.widget: QTextEdit = widget

    def emit(self, record):
        msg = self.format(record)
        self.widget.setReadOnly(False)
        self.widget.insertPlainText(msg + '\n')
        self.widget.setReadOnly(True)
